<!DOCTYPE html>
<html class="loading" lang="zh-CN" data-textdirection="ltr">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui" />
  <meta name="author" content="PIXINVENT" />
  <title>666后台管理系统</title>
  <link rel="stylesheet" type="text/css" href="app-assets/css/vendors.css" />
  <link rel="stylesheet" type="text/css" href="app-assets/css/vertical-menu.css" />
  <link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css" />
</head>

<body>
  <div class="content-wrapper">
    <div class="content-header">
      <div class="content-header-left mb-2">
        <h3 class="content-header-title mb-0">购物车</h3>
      </div>
    </div>
    <div class="card">
      <div class="card-content">
        <div class="card-body">
          <div class="funcbtn clearfix">
            <div class="pull-left">
              <a class="btn btn-info" href="采购商品.html">继续添加</a>
            </div>
            <div class="pull-right">
              <a class="btn btn-info" href="#" id="createOrder">生成采购单</a>
            </div>
          </div>
          <div class="tablebox1">
            <table class="table">
              <thead>
                <tr>
                  <th>图片</th>
                  <th>商品名称</th>
                  <th>数量</th>
                  <th>采购单价</th>
                  <th>小计</th>
                </tr>
              </thead>
              <tbody id="list"></tbody>
            </table>
          </div>
          <div style="font-weight: bold; color: black;">总计: <span id="shopListSum"></span>元</div>
        </div>
      </div>
    </div>
  </div>

  <script src="app-assets/js/vendors.min.js" type="text/javascript"></script>
  <script src="app-assets/js/app-menu.js" type="text/javascript"></script>
  <script src="app-assets/js/app.js" type="text/javascript"></script>
  <script src="app-assets/js/echarts.min.js" type="text/javascript"></script>
  <script src="app-assets/laydate/laydate.js" type="text/javascript"></script>

  <script type="module">
    //模块化引入
    //设置 type="module"
    //引入购物车js
    import {
      updateCart,
      clearCart,
      delProduct,
    } from "./app-assets/js/cart.js";

    function onladOk() {
      //获取购物车中的数据
      let cart = JSON.parse(localStorage.getItem("cart"));

      //accumulator:累计值  product：数组中当前被处理的元素   0：起始值
      const total = cart.reduce((accumulator, product) => {
        return accumulator + product.quantity * product.purchasePrice;
      }, 0);
      $("#shopListSum").html(total.toFixed(2));
      $("#list").empty();
      cart.forEach((product) => {
        let tr =
          `<tr>
              <td><img width='220px' src="http://localhost:24080/` + product.imageUrl + `"></td>
              <td>` + product.productName + `</td>
              <td>
                <div class="input-group">
                  <button class="btn btn-outline-secondary" type="button"
                  onclick=addQuantity(` + product.productId + `)>+</button>
                  <input type="text" value="` + product.quantity + `" />
                  <button class="btn btn-outline-secondary" type="button" onclick=subtractQuantity(` + product.productId + `)>-</button>
                </div>
              </td>
              <td>` + product.purchasePrice + `</td><td>¥` + (product.quantity * product.purchasePrice).toFixed(2) + `</td>
              <td><button type="button" class="btn btn-danger" onclick='del(` + product.productId + `)'>删除</button></td> 
            </tr>`;
        $("#list").append(tr);
      });
    }
    //页面加载
    $(function () {
      onladOk();
    });
    //点击加号
    window["addQuantity"] = function (productId) {
      updateCart(productId, "add");
      onladOk();
    };

    //点击减号
    window["subtractQuantity"] = function (productId) {
      updateCart(productId, "subtract");
      onladOk();
    };
    //删除商品
    window["del"] = function (productId) {
      delProduct(productId);
      onladOk();
    };

    //点击生成采购单
    $("#createOrder").on("click", function (e) {

      // 阻止默认行为
      e.preventDefault();

      // 获取购物车中的数据
      let cart = JSON.parse(localStorage.getItem("cart"));

      // 检查 cart 是否存在且不是空数组
      if (cart && cart.length > 0) {
        // 映射购物车数据以创建一个包含产品ID和数量的新数组
        let arr = cart.map((item) => {
          return {
            productId: item.productId,
            quantity: item.quantity
          };
        });

        console.log(arr);

        // 将数据传递到后台生成采购单
        $.ajax({
          url: "http://localhost:24080/purchaseOrders",
          type: "post", // 注意：通常创建资源应该使用 POST 方法，而不是 GET
          dataType: "json",
          contentType: "application/json",
          data: JSON.stringify(arr), // 发送的数据需要转换成字符串形式
          success: function (response) {
            if (response.status) {
              // 清空购物车
              clearCart();
              // 跳转到采购订单页面
              window.location.href = '采购订单.html'; // 在这里添加跳转逻辑
            } else {
              alert(response.message);
            }
          },
          error: function (jqXHR, textStatus, errorThrown) {
            alert('请求失败: ' + textStatus + ', 错误信息: ' + errorThrown);
          }
        });
      } else {
        alert("购物车为空，无法生成采购单！");
      }
    });


  </script>
</body>

</html>